package com.leyou.user.service;

import com.leyou.common.utils.CodecUtils;
import com.leyou.common.utils.NumberUtils;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.pojo.User;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author CHERRY
 * @date 2018-09-15-10:38
 */
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private StringRedisTemplate template;

    String KEY_PREFIX = "user:code:phone:";

    @Autowired
    private static final Logger LOGGER = LoggerFactory.getLogger(UserService.class);

    /**
     * 查询用户数据是否存在
     *
     * @param data
     * @param type
     * @return
     */
    public Boolean checkUserData(String data, Integer type) {
        User user = new User();
        switch (type) {
            case 1:
                user.setUsername(data);
                break;
            case 2:
                user.setPhone(data);
                break;
            default:
                return null;
        }

        return this.userMapper.selectCount(user) == 0;
    }

    /**
     * 生成验证码并发送
     *
     * @param phone
     */
    public Boolean createCaptchaAndSendMessage(String phone) {

        if (StringUtils.isBlank(phone)) {
            return false;
        }
        try {
            //生成验证码
            String code = NumberUtils.generateCode(6);

            //保存验证码到redis 5分钟过期
            this.template.opsForValue().set(KEY_PREFIX + phone, code, 5, TimeUnit.MINUTES);

            //发送短信
            Map<String, String> map = new HashMap<>();
            map.put("phone", phone);
            map.put("code", code);

            this.amqpTemplate.convertAndSend("LEYOU.SMS.EXCHANGE", "sms.captcha", map);

            return true;
        } catch (AmqpException e) {

            LOGGER.error("发送短信验证码异常", e);
            return false;
        }

    }

    /**
     * 注册用户
     *
     * @param user
     * @param code
     * @return
     */
    public Boolean register(User user, String code) {

        //redis 中保存的验证码
        String redisCode = this.template.opsForValue().get(KEY_PREFIX + user.getPhone());

        if (!StringUtils.equals(redisCode, code)) {
            //验证码错误
            return false;
        }

        //生成盐
        String salt = CodecUtils.generateSalt();
        user.setSalt(salt);
        //密码加密
        user.setPassword(CodecUtils.md5Hex(user.getPassword(), salt));

        user.setId(null);
        user.setCreated(new Date());

        //通用mapper
        boolean boo = this.userMapper.insertSelective(user) == 1;

        //注册成功，清理redis
        if (boo) {
            this.template.delete(KEY_PREFIX + user.getPhone());
        }

        return boo;

    }

    /**
     * 登录用户
     *
     * @param username
     * @param password
     * @return
     */
    public User login(String username, String password) {

        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            return null;
        }

        //创建查询条件，根据手机、用户名或邮箱
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username", username).orEqualTo("phone", username);
        //通用mapper查询
        User user = this.userMapper.selectOneByExample(example);
        //用户不存在
        if (user == null) {
            return null;
        }
        //密码正确
        if (user.getPassword().equals(CodecUtils.md5Hex(password, user.getSalt()))) {
            return user;
        } else {
            return null;
        }
    }
}
